package com.spzx.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.RemoteOrderService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author ChenXing
 * @Description
 * @Create 2024/8/19 0:38
 */

@Service
public class AlipayServiceImpl implements IAlipayService {

     @Autowired
     private IPaymentInfoService paymentInfoService;

     @Autowired
     private RemoteOrderService remoteOrderService;

     @Autowired
     private RabbitService rabbitService;

    // 调用支付宝sdk的api,生成支付表单
  private final  AlipayClient alipayClient = new DefaultAlipayClient(
            AlipayCommonParams.GATEWAY,
            AlipayCommonParams.APP_ID,
            AlipayCommonParams.SPZX_PRIVATEKEY,// 自己的私钥，用来加密
            AlipayCommonParams.FORMAT,
            AlipayCommonParams.CHARSET,
            AlipayCommonParams.ALI_PUBLICKEY,// 阿里的公钥用来解密
            AlipayCommonParams.SIGNTYPE);


    @SneakyThrows
    @Override
    public String submitAlipay(String orderNo) {

     OrderInfo orderInfo = remoteOrderService.getOrderInfoByOrderNo(orderNo, SecurityConstants.INNER).getData();



        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(" http://ya87j7.natappfree.cc/payment/alipay/callback/notify");
        //同步跳转地址，仅支持http/https
        request.setReturnUrl("http://192.168.9.105/#/pages/money/paySuccess");
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderNo);
        //支付金额，最小值0.01元
        bizContent.put("total_amount", orderInfo.getTotalAmount());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "商品总价:");

        /******可选参数******/
        //手机网站支付默认传值QUICK_WAP_WAY
        bizContent.put("product_code", "QUICK_WAP_WAY");
//bizContent.put("time_expire", "2022-08-01 22:00:00");

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request,"GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setUserId(orderInfo.getUserId());
        String content = "";
        for(OrderItem item : orderInfo.getOrderItemList()) {
            content += item.getSkuName() + " ";
        }
        paymentInfo.setContent(content);
        paymentInfo.setAmount(orderInfo.getTotalAmount());
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentStatus(0);
        paymentInfoService.save(paymentInfo);

        return pageRedirectionData;
    }

    @Override
    public void alipayNotify(Map<String, String> paramMap) {

        // 修改支付状态 paymentInfo.setPaymentStatus 改为1

       String orderNo = paramMap.get("out_trade_no");
        PaymentInfo paymentInfo = paymentInfoService.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        paymentInfo.setPaymentStatus(1);
        paymentInfoService.saveOrUpdate(paymentInfo);

        // 修改订单服务状态  order_status 改为 1 （改完后 通知product 修改库存）

        rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY,MqConst.ROUTING_PAYMENT_PAY,orderNo);
    }

    @Override
    public void closePayment(String orderNo) {

        // 查询本地交易记录
        PaymentInfo paymentInfo = paymentInfoService.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));

        // 判断交易记录是否存在，并且未支付
        if (paymentInfo != null && paymentInfo.getPaymentStatus().intValue() == 0) {

            //3 产生本地交易记录 要进行关闭
            paymentInfo.setPaymentStatus(-1);
            paymentInfoService.updateById(paymentInfo);

            //4.查询支付宝交易记录是否关闭
            Boolean flag = this.checkAlipayPayment(orderNo);
            if (flag) {
                this.closeAlipayTrade(orderNo);
            }
        }
    }
    private Boolean checkAlipayPayment(String orderNo) {
        try {
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            request.setBizContent(bizContent.toString());
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                //交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
                if ("WAIT_BUYER_PAY".equals(response.getTradeStatus())) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }



    private Boolean closeAlipayTrade(String orderNo) {
        try {
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            request.setBizContent(bizContent.toString());
            AlipayTradeCloseResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("支付宝关闭交易调用成功");
                return true;
            } else {
                System.out.println("支付宝关闭交易调用失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
